#include "Netvars.h"
#include "HL2Interface.h"
#include "Includes.h"

NetvarManager g_pNetvars;

int NetvarManager::CrawlTableForOffset(RecvTable *pTable, const char *name)
{
	int addOffset = 0;
	for(int i = 0; i < pTable->GetNumProps(); i++)
	{
		RecvProp *pProp = pTable->xGetProp(i);

		if(pProp->GetDataTable() && pProp->GetDataTable()->GetNumProps() > 0)
		{
			int iOffset = CrawlTableForOffset(pProp->GetDataTable(), name);
			if(iOffset)
			{
				addOffset += pProp->GetOffset() + iOffset;
			}
		}

		string propName(pProp->GetName());
		if(_stricmp(name, propName.c_str()))
			continue;

		return pProp->GetOffset() + addOffset;
	}
	return addOffset;
}

int NetvarManager::GetNetvarOffset(const char *table, const char *name)
{
	ClientClass *pClass = g_pInterfaces.g_pClient->GetAllClasses(); // TODO get interface!
	for(; pClass; pClass = pClass->m_pNext)
	{
		RecvTable *pTable = pClass->m_pRecvTable;
		if(pTable->GetNumProps() <= 1)
			continue;

		if(_stricmp(table, pTable->GetName()))
			continue;

		int iResult = CrawlTableForOffset(pTable, name);
		
		return iResult;
	}
	return NULL;
}

void NetvarManager::PullOffsets()
{
	Offsets::m_iTeamNum	   = GetNetvarOffset("DT_BasePlayer",			 "m_iTeamNum");
	Offsets::m_lifeState	   = GetNetvarOffset("DT_BasePlayer",			 "m_lifeState");
	Offsets::m_iHealth	   = GetNetvarOffset("DT_BasePlayer",			 "m_iHealth");
	Offsets::m_fFlags		   = GetNetvarOffset("DT_BasePlayer",			 "m_fFlags");
	Offsets::m_ArmorValue	   = GetNetvarOffset("DT_CSPlayer",				 "m_ArmorValue");
	Offsets::m_hActiveWeapon = GetNetvarOffset("DT_BaseCombatCharacter",	 "m_hActiveWeapon");
	Offsets::m_vecVelocity   = GetNetvarOffset("DT_BasePlayer",			 "m_vecVelocity");
	Offsets::m_vecOrigin	   = GetNetvarOffset("DT_BasePlayer",			 "m_vecOrigin");
	Offsets::m_vecPunchAngle = GetNetvarOffset("DT_BasePlayer",			 "m_vecPunchAngle");
	Offsets::m_iFOV		   = GetNetvarOffset("DT_BasePlayer",			 "m_iFOV");
	Offsets::m_vecViewOffset = GetNetvarOffset("DT_BasePlayer",			 "m_vecViewOffset");
}